//.pragma library

//ユーザー認証関係
var SETTING_KEY_ACCESS_TOKEN = "ACCESS_TOKEN";
var SETTING_KEY_ACCESS_TOKEN_SECRET = "ACCESS_TOKEN_SECRET";
var SETTING_KEY_ACCESS_SCREEN_NAME = "ACCESS_SCREEN_NAME";
var SETTING_KEY_ACCESS_USER_ID = "ACCESS_USER_ID";


function readData(key) {
    var ret = undefined;
    db().transaction(
        function(tx) {
            createTable(tx);

            var rs = tx.executeSql('SELECT value FROM Settings WHERE key=?', key);

            if (rs.rows.length > 0) {
                ret = rs.rows.item(0).value;
            }
        }
    )
    return ret;
}

function saveData(key, value) {
    db().transaction(
        function(tx) {
            createTable(tx);

            var currentValue = readData(key);
            if (currentValue != value) {
                if (currentValue !== undefined) {
                    tx.executeSql('UPDATE Settings SET value = ? WHERE key = ?', [ value, key ]);
                } else {
                    tx.executeSql('INSERT INTO Settings VALUES(?, ?)', [ key, value ]);
                }
            }
        }
    )
}

function readAccountData(){
    var ret = [];
    db().transaction(
        function(tx){
            createAccountTable(tx);

            var rs = tx.executeSql('SELECT number, token, token_secret, screen_name, user_id FROM Account');

            if (rs.rows.length > 0) {
                for(var i=0;i<rs.rows.length;i++){
                    ret.push({"number": rs.rows.item(i).number
                                 , "token": rs.rows.item(i).token
                                 , "token_secret": rs.rows.item(i).token_secret
                                 , "screen_name": rs.rows.item(i).screen_name
                                 , "user_id": rs.rows.item(i).user_id});
                }
            }
        }
    )
    return ret;
}

function saveAccountData(datas){//number, token, token_secret, screen_name, user_id){
    db().transaction(
        function(tx){
            createAccountTable(tx);

                    // 一旦削除
                    tx.executeSql("DELETE FROM Account");

                    for(var i=0; i<datas.length; i++){
                        tx.executeSql('INSERT INTO Account VALUES(?, ?, ?, ?, ?)'
                                      , [ datas[i].number, datas[i].token, datas[i].token_secret
                                         , datas[i].screen_name, datas[i].user_id ]);

                    }

        }
    )
}

function db() {
    return openDatabaseSync("REWITQ0.8", "1.0", "Settings storage for RewitQ", 10000);
}

function createTable(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS Settings(key TEXT, value TEXT)');
}

function createAccountTable(tx){
    tx.executeSql('CREATE TABLE IF NOT EXISTS Account(number TEXT, token TEXT, token_secret TEXT, screen_name TEXT, user_id TEXT)');
}
